package com.ityy.ruiji.service.impl;

import com.ityy.ruiji.common.R;
import com.ityy.ruiji.dao.AddressBookDao;
import com.ityy.ruiji.entity.AddressBook;
import com.ityy.ruiji.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired(required = false)
    private AddressBookDao addressBookDao;


    @Override
    public R finAll(AddressBook addressBook) {
        List<AddressBook> addressBookList = addressBookDao.finAll(addressBook);
        return R.success(addressBookList);
    }

    @Override
    @Transactional
    public R defaul(AddressBook addressBook) {
        //1. 把该用户地址全部修改为非默认
        addressBookDao.removeDefaultAddress(addressBook.getUserId());
        //2 重新设置当前地址为默认地址
        addressBookDao.updateDefaultAddress(addressBook);
        return R.success(addressBook);
    }

    @Override
    public R save(AddressBook addressBook) {
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBookDao.save(addressBook);
        return R.success("添加成功");
    }

    @Override
    public R<AddressBook> finById(Long id) {
        AddressBook addressBook = addressBookDao.finById(id);
        return R.success(addressBook);
    }

    @Override
    public R update(AddressBook addressBook) {
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBookDao.update(addressBook);
        return R.success("修改成功成功");
    }

    @Override
    public R deleteById(Long ids) {
        addressBookDao.deleteById(ids);
        return R.success("删除成功");
    }

    @Override
    public AddressBook getDefaultAddress(Long currentId) {
        return addressBookDao.getDefaultAddress(currentId);
    }
}
